package com.ruoyi.upload.controller;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.entity.templateentity.Template;
import com.ruoyi.common.entity.uploadentity.Upload;
import com.ruoyi.common.mapper.TemplateMapper;
import com.ruoyi.common.utils.LogUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileTypeUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.upload.config.Constant;
import com.ruoyi.upload.service.UploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

@RestController
@RequestMapping("/upload")
@CrossOrigin
public class UploadController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    private UploadService uploadService;

    @Autowired
    private TemplateMapper templateMapper;

    @Autowired
    private Constant constant;


    /**
     * 上传模板文件
     * @param file
     * @return fileName fileType 文件名
     * @throws IOException
     */
//    @PreAuthorize("@ss.hasPermi('UploadsAndDownloads:UploadAndDownload:uploadTemplate')")
    @PostMapping("/uploadfile")
    public AjaxResult uploadFile(@RequestParam("template") MultipartFile file) throws Exception {
       if (!file.isEmpty()){
           Upload upload = uploadService.upLoad(file);
           if (upload.isSuccess()){
               //id fileType fileName
               return AjaxResult.success(upload);
           }else
               return AjaxResult.error(upload.getResultMsg());
       }else
           return AjaxResult.error("文件不能为空！");
    }

//    /**
//     * 批量上传模板文件
//     * @param file
//     * @return fileName fileType 文件名
//     * @throws IOException
//     */
////    @PreAuthorize("@ss.hasPermi('UploadsAndDownloads:UploadAndDownload:uploadTemplate')")
//    @PostMapping("/uploadfile")
//    public AjaxResult uploadFile(@RequestParam("template") MultipartFile[] file) throws Exception {
//        for (int i = 0; i < file.length; i++) {
//            if (file[i].isEmpty())
//                return AjaxResult.error("请上传附件！");
//            if (!FileTypeUtils.getFileType(file[i].getOriginalFilename()).equals("doc"))
//                return AjaxResult.error("文件类型错误！");
//            }
//        List<Upload> uploadList = uploadService.upLoad(file);
//        return AjaxResult.success(uploadList);
//    }


//    /**
//     * 文件上传
//     * @param file
//     * @return fileName 文件名
//     * @throws IOException
//     */
//    @PreAuthorize("@ss.hasPermi('UploadsAndDownloads:UploadAndDownload:upload')")
//    @PostMapping("/uploadfile")
//    public AjaxResult uploadFile(@RequestParam("docfile") MultipartFile file) throws IOException {
//        if (!file.isEmpty()){
//           try {
//               //上传路径
//               System.out.println("getOriginalFilename---"+file.getOriginalFilename());
//               String filePath = RuoYiConfig.getTemplatePath();
//               String fileName  = FileUploadUtils.upload(filePath,file);
//               System.out.println(fileName);
//               return AjaxResult.success(fileName);
//           }catch (Exception e){
//               LogUtils.getBlock(e);
//               e.printStackTrace();
//               return AjaxResult.error("上传失败");
//           }
//        }else {
//            return AjaxResult.error("请选择附件");
//        }
//    }

    /**
     * 通用下载
     * @param resource 文件全路径
     * @return
     * @throws Exception
     */
    @GetMapping("/download/{resource}")
    public void download(@PathVariable("/resource") String resource, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try
        {
            //资源路径
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = resource;
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 模板下载
     * @param id
     * @return
     */
    @GetMapping("/download")
    public void downloadTemplate(String id,HttpServletRequest request, HttpServletResponse response) throws Exception{
        Template template = new Template();
        template.setId(id);
        List<Template> list = templateMapper.query(template);
        for (Template template1 : list) {
            System.out.println(template1.getFileName());
        }
        try
        {
            String fileName = list.get(0).getFileName();
            String resource = constant.getDOWNLOAD_PATH()+fileName;
            //资源路径
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = resource;
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

}
